package com.tools.cleanmaster.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.controller.MediaHelper;
import com.tools.cleanmaster.controller.TrashHandler;
import com.tools.cleanmaster.manager.TrashManager;
import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.TrashesData;
import com.tools.cleanmaster.model.item.ImageTrashBucket;
import com.tools.cleanmaster.model.item.ImageTrashItem;
import com.tools.cleanmaster.model.item.TrashItem;
import com.tools.cleanmaster.ui.adapter.TrashImageShowAdapter;
import com.tools.cleanmaster.ui.view.ToastHelper;
import com.tools.cleanmaster.ui.view.header.HeadHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * desc: 展示图片分类下（如：camera、Screenshots 等）的所有图片
 * date: 2018/7/4 11:41
 * author: ancun
 */
public class ImageShowActivity extends DeepActivity {

    public static final String BUCKET_ID = "bucket_id";
    public static final String BUCKET_TITLE = "bucket_title";
    private static final String TAG = "ImageShowActivity";
    private String mBucketId = "";
    private String mBucketTitle = "";
    private List<ImageTrashItem> mImages = new ArrayList<ImageTrashItem>();
    private GridView mGridView;
    private TextView mCountText;
    private Button mButton;
    private TrashImageShowAdapter mAdapter;
    private ImageTrashBucket mBucket;
    private List<TrashItem> mTrashBuckets;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_show);

        StatusBarUtil.setTransparentForImageView(this, findViewById(R.id.titlebar));
        StatusBarUtil.setTranslucentForNavigation(this, findViewById(R.id.root));
        init();
        initData();
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            mBucketId = intent.getStringExtra(BUCKET_ID);
            mBucketTitle = intent.getStringExtra(BUCKET_TITLE);
        }

        boolean isTitle = TextUtils.isEmpty(mBucketTitle);
        if (isTitle) {
            HeadHelper.setupMainHeader(this, R.id.titlebar, R.string.trash_clean_image_files, this)
                    .hideSettingButton().setBackgroundColor();
        } else {
            HeadHelper.setupMainHeader(this, R.id.titlebar, mBucketTitle, this)
                    .hideSettingButton();
        }

        mGridView = findViewById(R.id.gridview);
        mCountText = findViewById(R.id.count);
        mButton = findViewById(R.id.bottom_button);
        setCountText();
        setDeleteButton(mButton);
    }

    private void initData() {
        TrashHandler trashHandler = TrashManager.getInstance().getTrashHandler(true);
        if (trashHandler == null) {
            finish();
            return;
        }

        TrashesData trashesData = trashHandler.getTrashesData();
        if (trashesData == null) {
            finish();
            return;
        }

        mTrashBuckets = trashesData.getTrashesByType(TrashType
                .IMAGE_FILE);
        if (mTrashBuckets == null) {
            finish();
            return;
        }
        int size = mTrashBuckets.size();
        for (int i = 0; i < size; i++) {
            mBucket = (ImageTrashBucket) mTrashBuckets.get(i);
            if (mBucket == null) {
                continue;
            }
            if (mBucketId.equals(mBucket.id)) {
                mImages = mBucket.imageList;
                break;
            }
        }

        if (mImages != null && !mImages.isEmpty()) {

            //初始化Image勾选状态
            for (ImageTrashItem item : mImages) {
                item.isSelected = false;
            }

            mAdapter = new TrashImageShowAdapter(this, mImages);
            mGridView.setAdapter(mAdapter);
        } else {
            finish();
            return;
        }

        mAdapter.setItemShowCallback(new TrashImageShowAdapter.OnClickCallback() {
            @Override
            public void onClick(int position, String path) {
                Intent intent = new Intent(ImageShowActivity.this, MediaShowActivity.class);
                intent.putExtra(MediaShowActivity.PATH, path);
                startActivity(intent);
            }
        });

        mAdapter.setDeleteCallback(new TrashImageShowAdapter.OnDeleteCallback() {
            @Override
            public void onClick(int position, TrashItem item) {
                if (item.isSelected) {
                    mDeleteItemCount++;
                    mDeleteItemSize += item.size;
                } else {
                    mDeleteItemCount--;
                    mDeleteItemSize -= item.size;
                }

                setCountText();
                setDeleteButton(mButton);

            }
        });

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogInfo bulider = new DialogInfo();
                bulider.setCount("" + mDeleteItemCount).setSize(mDeleteItemSize);
                showDeleteDialog(bulider);
            }
        });
    }

    private void setCountText() {
        if (mDeleteItemCount > 0) {
            mCountText.setTextColor(getResources().getColor(R.color.v2_color_main_title));
        } else {
            mCountText.setTextColor(getResources().getColor(R.color.trash_image_unselect_color));
        }
        mCountText.setText(getString(R.string.trash_image_selete, "" + mDeleteItemCount));
    }

    @Override
    protected void onDelete() {
        List<TrashItem> deleteList = new ArrayList<TrashItem>();
        for (ImageTrashItem item : mImages) {
            if (item.isSelected) {
                long size = mBucket.size - item.size;
                mBucket.size = size >= 0 ? size : 0;
                mBucket.count--;
                deleteList.add(item);
            }
        }

        if (!deleteList.isEmpty()) {
            mImages.removeAll(deleteList);
            mAdapter.notifyDataSetChanged();
            delete(deleteList);
            if (mImages.isEmpty()) {
                mTrashBuckets.remove(mBucket);
                onBackPressed();
                ToastHelper.create(getApplicationContext(), R.string.trash_delete_success,
                        Toast.LENGTH_LONG).show();
            }

            mDeleteItemCount = 0;
            mDeleteItemSize = 0;

            setCountText();
            setDeleteButton(mButton);
        }
    }

    @Override
    protected void delete(final List<TrashItem> items) {
        ThreadPool.runOnPool(new Runnable() {
            @Override
            public void run() {
                MediaHelper.getHelper(getContentResolver()).deleteMediaImage(items);

                for (TrashItem trashItem : items) {
                    ImageTrashItem item = (ImageTrashItem) trashItem;
                    if (!TextUtils.isEmpty(item.imagePath)) {
                        File deleteFile = new File(item.imagePath);
                        deleteFile.delete();
                    }
                    if (!TextUtils.isEmpty(item.thumbnailPath)) {
                        File imageFile = new File(item.thumbnailPath);
                        imageFile.delete();
                    }
                }
            }
        });
    }
}
